<template>
    <van-nav-bar title="地址列表" left-text="" left-arrow @click-left="goBack" />
    <!-- 订单 -->
    <van-address-list v-if="action" v-model="chosenAddressId" :list="addresslist" default-tag-text="默认" @add="onAdd"
        @edit="onEdit" @select="chooseed" />
    <!-- 个人中心 -->
    <van-address-list v-else v-model="chosenAddressId" :list="addresslist" default-tag-text="默认" @add="onAdd"
        @edit="onEdit" @select="selected" />
</template>
<script setup>
const { proxy } = getCurrentInstance()
const LoginUser = reactive(proxy.$cookies.get('LoginUser'));
const action = ref(proxy.$route.query.action ?? '')
const goBack = () => {
    if (action.value == 'order') {
        proxy.$router.go(-1)
    } else {
        proxy.$router.push('/business/index')
    }

}
const chosenAddressId = ref(null);
const addresslist = ref([]);
const onAdd = () => { proxy.$router.push('/business/address/add') }
onBeforeMount(() => {
    getAddressData()
})
const getAddressData = async () => {
    let result = await Api.AddressIndex({
        busid: LoginUser.id,
    })
    if (result.code == 1) {
        addresslist.value = []
        result.data.forEach(item => {
            addresslist.value.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                isDefault: item.status == '1' ? true : false,
                address: item.region_text + item.address
            })

            if (item.status == '1') {
                chosenAddressId.value = item.id
            }
        })
    } else {
        error(result.msg);
    }
}
const onEdit = (val) => {
    proxy.$router.push({
        path: '/business/address/edit',
        query: {
            addressid: val.id
        }
    })
}
// 切换默认地址
const selected = async (val) => {
    let result = await Api.AddressCheck({
        busid: LoginUser.id,
        addressid: val.id
    })
    if (result.code == 1) {
        getAddressData()
    } else {
        error(result.msg);
    }
}

// 选中收货地址
const chooseed = (val) =>{
    proxy.$cookies.set("address", {
        id: val.id,
        consignee: val.name,
        mobile: val.tel
    });
    goBack()
}
</script>